<!--
 * @Date: 2023-08-02 13:50:49
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-05-29 17:14:51
 * @FilePath: \NingxiangElderlyCare\src\views\datacenter\comprehensiveQueries\components\quickStatistics\components\operateForm\index.vue
-->
<template>
	<div>
		<slot></slot>
		<section class="condition">
			<p class="line-label">统计条件</p>
			<div class="condition-box">
				<el-form label-width="120px">
					<el-form-item label="统计日期">
						<el-radio-group v-model="formMod.dateType">
							<el-radio label="全部" :value="1"></el-radio>
							<el-radio label="选择时间" :value="2"></el-radio>
							<DateBetween v-show="formMod.dateType == 2" v-model="formMod.date"></DateBetween>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="统计维度">
						<section class="w-100">
							<el-radio-group v-model="formMod.dimension" @change="handleDimensionChange">
								<el-radio v-for="(item, index) in dimensionOption" :key="index" :value="item.id" :label="item.name"></el-radio>
							</el-radio-group>
							<DimensionSwitch
								:key="formMod.dimension"
								:dimension="formMod.dimension"
								:dimensionOption="dimensionOption"
								v-model:model-value="formMod.dimensionList"
								@nowDimen="handleDimenChange"
							></DimensionSwitch>
						</section>
					</el-form-item>

					<el-form-item label="统计主体及其他统计条件">
						<div class="w-100">
							<el-steps :active="active" align-center>
								<el-step
									v-for="(item, index) in TabsList"
									:key="index"
									:title="item.label"
									:description="item.description"
									@click="handleSetpChange(item, index)"
								/>
							</el-steps>
							<FieldSelect
								:key="formMod.dimension"
								:relateProp="dimensionItem.reserve?.relateProp"
								v-if="!loading"
								:value="selected"
								:data="dataList"
								v-show="active == 1"
								@change="handleChange"
							></FieldSelect>
							<!-- 统计 -->
							<StatisticsPage :dragData="dragData" v-show="active == 2" :key="selected" @cell-change="onChange"> </StatisticsPage>
							<!-- 关联其他数据类型的统计条件 -->
							<FieldFilterSelect
								:dragData="dragData"
								v-show="active == 3"
								:key="selected"
								:baseType="selected"
								@field-change="handleFieldChange"
							></FieldFilterSelect>
						</div>
					</el-form-item>
				</el-form>
			</div>
		</section>

		<section class="condition">
			<p class="line-label">已选条件</p>
			<div class="condition-box">
				<el-form label-width="120px">
					<el-form-item label="统计日期">
						<el-tag color="#E7E7E7" style="color: #000" :hit="false" type="info">
							{{ formMod.date || '全部' }}
						</el-tag>
					</el-form-item>
					<el-form-item label="统计维度">
						<el-space style="display: flex; flex-flow: row wrap; gap: 10px">
							<el-tag color="#E7E7E7" v-for="(item, index) in formMod.dimensionList" :key="index" style="color: #000" :hit="false" type="info">
								{{ item }}
							</el-tag>
						</el-space>
					</el-form-item>
					<el-form-item label="统计主体及其他统计条件">
						<div>
							<el-space>
								<span> {{ baseConditions.name }}</span>
								<el-tag color="#E7E7E7" style="color: #000" type="info" v-for="(item, index) in baseConditions.publicLogicList" :key="index">
									{{ item.name }}:{{ item.fieldValue }}
								</el-tag>
							</el-space>
						</div>

						<div>
							<el-space v-for="(v, k) in fieldConditions" :key="k">
								<span> {{ k }}</span>
								<el-tag color="#E7E7E7" style="color: #000" type="info" v-for="(item, index) in v.publicLogicList" :key="index">
									{{ item.name }}:{{ item.fieldValue }}
								</el-tag>
							</el-space>
						</div>
						<div class="footer-but fc w-100">
							<el-button type="primary" @click="handleSearch">查询</el-button>
							<el-button @click="handleCleanCondition">清空条件</el-button>
						</div>
					</el-form-item>
				</el-form>
			</div>
		</section>

		<section class="condition">
			<p class="line-label">统计结果</p>
			<div class="condition-box" v-if="dimensionTypeLabel">
				<div class="btn tr">
					<el-button type="primary" @click="handleSave">保存</el-button>
				</div>
				<el-table default-expand-all row-key="name" border :data="tableData" style="width: 100%" class="mt10" :key="reloadKey">
					<el-table-column :label="dimensionTypeLabel" align="left" prop="name">
						<el-table-column prop="name" label="所属区" v-if="!dimensionTypeLabel.includes('行政区划')" align="left" />
					</el-table-column>
					<el-table-column :label="baseConditions.name" align="left">
						<el-table-column prop="value" :label="valueLabelTitle" align="left" />
					</el-table-column>
				</el-table>
			</div>
		</section>
		<section class="condition">
			<p class="line-label">图表展示</p>
			<div class="condition-box">
				<AplidCharts type="BasicBar" :option="option" style="height: 100%" ref="chartBarEl"></AplidCharts>
			</div>
		</section>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import DateBetween from '@/views/aplid/DateBetween/index.vue'
import FieldSelect from './FieldSelect/index.vue'
import StatisticsPage from './StatisticsPage/index.vue'
import FieldFilterSelect from './FieldFilterSelect/index.vue'
import DimensionSwitch from './DimensionSwitch/index.vue'
import { treeTransArray } from '@/utils/util'

const emit = defineEmits(['refresh'])
const props = defineProps<{
	nowRowData?: any
}>()
const formMod: any = reactive({
	dimension: '',
	dimensionList: [],
	orgName: '',
	dimensionFieldName: '',
})

const tableData = ref([])
const active = ref(1)
const selected = ref(0)
const loading = ref(false)
const dragData = ref({})
const reloadKey = ref(0)
const TabsList = [
	{
		label: '步骤一',
		prop: 'dp_service_object',
		description: '统计主体',
	},
	{
		label: '步骤二',
		prop: 'dp_service_object_extend',
		description: '统计条件',
	},
	{
		label: '步骤三',
		prop: 'dp_service_object_other',
		description: '附加条件：',
	},
]

const dimensionOption = ref([])

let dataList = []
let baseConditions: any = ref([])
let fieldConditions: any = ref({})

const areaDimenOption = ref([])
const dimensionTypeLabel = ref('')
const valueLabelTitle = ref('')
const chartBarEl = ref(null)

const option = {
	color: ['#0052D9', '#00A870', '#ED7B2F'],
	dataset: {
		source: [],
	},
	dataZoom: [
		{
			type: 'inside',
			start: 0,
			end: 80,
		},
	],
	series: [
		{
			type: 'bar',
			barBorderRadius: [4, 4, 0, 0],
			barWidth: 15,
			emphasis: {
				shadowBlur: 10,
				shadowOffsetX: 0,
				shadowColor: 'rgba(0, 0, 0, 0.3)',
			},
		},
	],
}

const dimensionItem = computed(() => {
	return dimensionOption.value.find((item) => item.id == formMod.dimension) || {}
})

const handleDimensionChange = () => {
	active.value = 1
	selected.value = 0
	handleCleanCondition()
}

const next = () => {
	if (active.value++ > 3) active.value = 3
}
const handleSetpChange = (item, index) => {
	active.value = index + 1
}
const handleChange = (data, obj) => {
	selected.value = data
	dragData.value = obj
	next()
}
const onChange = (data, item) => {
	// 获取维度数据
	baseConditions.value = data
}

const handleFieldChange = (data, checkedList) => {
	fieldConditions.value = data
	valueLabelTitle.value = checkedList.map((item) => item.name).join('/')
}

const getConfig = () => {
	if (props.nowRowData.id) {
		apiMod.view_statisticalConfiguration_view(props.nowRowData.id).then((res) => {
			if (!res.data?.configurationInformation) return
			const config = JSON.parse(res.data?.configurationInformation || '{}')
			const { dimension, dimensionList, dimensionFieldName, dateType, date } = config.formMod || {}
			formMod.dimension = dimension
			formMod.dimensionList = dimensionList
			formMod.dimensionFieldName = dimensionFieldName
			formMod.dateType = dateType
			formMod.date = date
			baseConditions.value = JSON.parse(res.data?.statisticalConditions || '{}')
			fieldConditions.value = config.fieldConditions || {}
			dimensionTypeLabel.value = config.dimensionTypeLabel
			valueLabelTitle.value = config.valueLabelTitle
			dataList = config.dataList
			selected.value = config.selected
		})
	}

	loading.value = true
	apiMod
		.view_componentSettings_page({
			delFlag: 0,
			affiliation: 1,
			pageParaPO: {
				current: 1,
				size: 1000,
			},
		})
		.then((res) => {
			const { records } = res.data
			dataList = records
			dimensionOption.value = records.filter((item) => item.dimension == 1 && item.reserve?.dimensionType != 4)
			loading.value = false
		})
}

const handleDimenChange = (item) => {
	formMod.dimensionFieldName = item.code
	dimensionTypeLabel.value = item.name
}

const handleCleanCondition = () => {
	baseConditions.value = {}
	fieldConditions.value = {}
	dragData.value = {}
	selected.value = 0
	active.value = 1
	getConfig()
}
const handleSearch = () => {
	let deputyLogicList = []
	if (Object.values(fieldConditions.value).length == 0 && Object.values(baseConditions.value).length == 0) {
		ElMessage.warning('请选择查询条件!')
		return
	}
	Object.values(fieldConditions.value).map((item: any) => {
		item.publicLogicList.some((val) => {
			const associatedFields = item.associatedFields?.map((item) => item.field) || []
			deputyLogicList.push({
				...val,
				tableName: item.tableName,
				associatedFields: [...new Set(associatedFields)].toString(),
				type: 0,
			})
		})
	})

	const params = {
		tableName: baseConditions.value.tableName,
		dimensionFieldName: formMod.dimensionFieldName,
		dimensionLabels: formMod.dimensionList.join(','),
		publicLogicList: [
			{
				condition: 'in',
				fieldName: formMod.dimensionFieldName,
				fieldValue: formMod.dimensionList.join(','),
				type: 0,
			},
			...baseConditions.value.publicLogicList.map((item) => {
				item.type = 0
				return item
			}),
		],
		deputyLogicList: [...deputyLogicList],
	}
	if (formMod.dimensionFieldName == 'area_name' || formMod.dimensionFieldName == 'cr_area_name') {
		if (params.dimensionLabels.includes('区')) {
			params.dimensionFieldName = formMod.dimensionFieldName == 'area_name' ? 'area_name' : 'cr_area_name'
		} else if (params.dimensionLabels.includes('街道')) {
			params.dimensionFieldName = formMod.dimensionFieldName == 'area_name' ? 'street_name' : 'cr_street_name'
		} else if (params.dimensionLabels.includes('社区')) {
			params.dimensionFieldName = formMod.dimensionFieldName == 'area_name' ? 'community_name' : 'cr_community_name'
		}
		params.publicLogicList[0].fieldName = params.dimensionFieldName
	}

	apiMod.view_statistics_query(params).then((res) => {
		tableData.value =
			res.data?.map((item) => {
				return {
					...item,
					value: item.value || '0',
				}
			}) || []
		const source = tableData.value.length > 0 ? treeTransArray(tableData.value) : []

		reloadKey.value = Math.random()

		chartBarEl.value?.setOptions({
			dataset: {
				source: [
					['名称', '数量'],
					...source.map((item) => {
						return [item.name, item.value || 0]
					}),
				],
			},
		})
	})
}

const saveConfig = (data, cancelText: string, callBack?: Function) => {
	ElMessageBox.prompt('请输入组件名称', '保存组件？', {
		confirmButtonText: '保存',
		cancelButtonText: cancelText,
	})
		.then(({ value }) => {
			apiMod
				.view_statisticalConfiguration_add({
					name: value,
					...data,
				})
				.then(() => {
					emit('refresh')
					callBack('ok')
				})
		})
		.catch(() => {
			callBack('cancel')
		})
}

// 数据保存
const handleSave = () => {
	const query = {
		result: formMod,
		statisticalConditions: baseConditions.value,
		configurationInformation: {
			formMod: formMod,
			dataList: dataList,
			fieldConditions: fieldConditions.value,
			tableData: tableData.value,
			dimensionTypeLabel: dimensionTypeLabel.value,
			valueLabelTitle: valueLabelTitle.value,
			selected: selected.value,
		},
	}
	saveConfig(query, '返回', (res) => {
		if (res == 'ok') {
			emit('refresh')
		}
	})
}

onMounted(() => {
	getConfig()
})
</script>

<style scoped lang="scss">
:deep(.el-form-item__label) {
	font-family: 'Microsoft YaHei Bold';
	font-weight: 700;
	font-size: 16px;
	text-align: right;
	color: #1c1c28;
}

.condition {
	padding: 20px;

	.condition-box {
		margin: 16px;
		padding: 20px;
		background-color: #fff;
	}
}

.line-label {
	font-family: 'Microsoft YaHei Bold';
	font-weight: 700;
	font-size: 16px;
	text-align: left;
	color: #1c1c28;
	position: relative;
	z-index: 0;
	width: 100%;
	padding-left: 10px;

	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 6px;
		height: 100%;
		background: #0052d9;
		z-index: -1;
	}
}
</style>
